/*
 * wcsrv.c
 *
 *  Created on: Apr 1, 2012
 *      Author: root
 */


#include	"unp.h"

int
main(int argc, char **argv)
{
	int					listenfd, connfd;
	pid_t				childpid;
	socklen_t			clilen;
	struct sockaddr_in	cliaddr, servaddr;
	void				sig_chld(int);

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(5458);

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	Signal(SIGCHLD, sig_chld);	/* must call waitpid() */

	for ( ; ; ) {
		clilen = sizeof(cliaddr);
		if ( (connfd = accept(listenfd, (SA *) &cliaddr, &clilen)) < 0) {
			if (errno == EINTR)
				continue;		/* back to for() */
			else
				err_sys("accept error");
		}

		if ( (childpid = Fork()) == 0) {	/* child process */
			Close(listenfd);	/* close listening socket */
			str_echo(connfd);	/* process the request */
			exit(0);
		}
		Close(connfd);			/* parent closes connected socket */
	}
}

void
str_echo(int sockfd)
{
	ssize_t		n;
	int i;
	int cbyte = 0, cword = 0, cline = 0;
	int tbyte = 0, tword = 0, tline = 0;
	char		buf[MAXLINE];

	while (1){
		//Writen(sockfd, buf, n);
		n = read(sockfd, buf, MAXLINE);
		printf("%s", buf);
		if(buf[0] == '.'){
			memset(buf, 0, sizeof(buf));
			//fflush(buf);
			sprintf(buf, "Total byte count : %d, word count : %d, line count : %d\n", tbyte, tword, tline);
			printf("%s", buf);
			write(sockfd, buf, sizeof(buf));
			memset(buf, 0, sizeof(buf));
			fflush(buf);
		}
		else{
			for(i=0;i<n;i++){
				if(buf[i] == ' '){
					cword++;
					cbyte++;
				}
				else if(buf[i] == '\n'){
					cword++;
					cline++;
				}
				else
					cbyte++;
			}
		}
		memset(buf, 0, sizeof(buf));
		//fflush(stdout);
		sprintf(buf, "byte count : %d, word count : %d, line count : %d\n", cbyte, cword, cline);
		printf("%s", buf);
		write(sockfd, buf, sizeof(buf));
		memset(buf, 0, sizeof(buf));
		//fflush(stdout);
		tbyte = tbyte + cbyte, tword = tword + cword, tline = tline + cline;
		cbyte = 0, cword = 0, cline = 0;
	}
}

void
sig_chld(int signo)
{
	pid_t	pid;
	int		stat;

	while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0)
		printf("child %d terminated\n", pid);
	return;
}

